package com.ytkj.tradeserver.service.impl;

import com.ytkj.tradeserver.constant.ComConstants;
import com.ytkj.tradeserver.dao.IAttachmentFileDao;
import com.ytkj.tradeserver.entity.AttachmentFileVO;
import com.ytkj.tradeserver.entity.UserInfo;
import com.ytkj.tradeserver.service.iservice.IAttachmentFileService;
import com.ytkj.tradeserver.utils.StringOpUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Administrator on 2017/3/18.
 */
@Service
public class AttachmentFileServiceImpl implements IAttachmentFileService {

    private static Logger logger = Logger.getLogger(AttachmentFileServiceImpl.class);

    @Resource
    IAttachmentFileDao fileDao;

    public int savefileData(AttachmentFileVO file){
      return  fileDao.savefileData(file);
    }

    public void saveSingleFileData(String businessId,String businessType,UserInfo userInfo,HttpServletRequest request){
        //创建一个通用的多部分解析器
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        String webfilepath = request.getSession().getServletContext().getRealPath(ComConstants.UPLOAD_FILE_DIRECTORY);
        //判断 request 是否有文件上传,即多部分请求
        if(multipartResolver.isMultipart(request)){
            //转换成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            //取得request中的所有文件名
            Iterator<String> iter = multiRequest.getFileNames();
            while(iter.hasNext()){
                //记录上传过程起始时的时间，用来计算上传时间
                int pre = (int) System.currentTimeMillis();
                //取得上传文件
                CommonsMultipartFile file = (CommonsMultipartFile) multiRequest.getFile(iter.next());
                if(file != null){
                    try {
                        commonSaveFile( businessId, businessType, webfilepath,
                                userInfo, file);
                    } catch (Exception e) {
                        logger.error("单个上传附件保存失败：" + e.getMessage());
                    }
                }
            }
        }
    }

    public void saveMultiUploadFile(String businessId,String businessType,
                                    UserInfo userInfo,CommonsMultipartFile[] files,
                                    HttpServletRequest request){
        String webfilepath = request.getSession().getServletContext().getRealPath(ComConstants.UPLOAD_FILE_DIRECTORY);
        //判断file数组不能为空并且长度大于0
        if(files!=null && files.length>0){
            //循环获取file数组中得文件
            for(int i = 0;i<files.length;i++){
                CommonsMultipartFile file = files[i];
                // 判断文件是否为空
                if (!file.isEmpty()) {
                    try {
                        commonSaveFile( businessId, businessType, webfilepath,
                                 userInfo, file);
                    } catch (Exception e) {
                        logger.error("多个上传附件保存失败：" + e.getMessage());
                    }
                }
            }
        }
    }


    public List<AttachmentFileVO> queryFiles(AttachmentFileVO file) {
        return fileDao.queryFiles(file);
    }

    private void commonSaveFile(String businessId,String businessType,String webfilepath,
                               UserInfo userInfo,CommonsMultipartFile file) throws IOException {
        //取得当前上传文件的文件名称
        String myFileName = file.getOriginalFilename();
        String suffixstr = StringOpUtils.getSuffixStr(myFileName);
        //重命名上传后的文件名
        String filePathName = StringOpUtils.getUuidStr() + "." + suffixstr;
        //定义上传路径
        String path = webfilepath + "/" + filePathName;
        File localFile = new File(path);
        file.transferTo(localFile);

        AttachmentFileVO filevo = new AttachmentFileVO();
        filevo.setFileName(myFileName);
        filevo.setFilePathName(filePathName);
        filevo.setFileSuffix(suffixstr);
        filevo.setFileSize((int)file.getSize());
        filevo.setCreator(userInfo.getId());
        filevo.setLastUpdateUser(userInfo.getId());
        filevo.setFileDirectory(ComConstants.UPLOAD_FILE_DIRECTORY);
        filevo.setType(businessType);
        filevo.setBusinessId(businessId);
        savefileData(filevo);
    }

}
